import 'package:eshi/app/Extension.dart';
import 'package:eshi/app/shi/data/HistoryMarks.dart';
import 'package:eshi/app/shi/data/History.dart';
import 'package:eshi/app/shi/data/SearchResult.dart';
import 'package:eshi/app/shi/data/parse/IndentParser.dart';

/// 历史节点
/// 
class HistoryPoint{
  /// 节点开始时间
  late int startTime;
  /// 节点结束时间
  late int endTime;
  //时长
  late String lenght;
  /// 节点名称
  String name="";
  /// 节点的数据
  Map<String,dynamic> data={};
  //排序后的数序id
  int index=0;
  List<String> getTextData({bool hasComment=true}) {
    var rt=<String>[];
    data.forEach((k,v){
        var tPage = "";
        if(v is String){
          if(data.length>1) tPage+="$k\n";
          if(data.length>1){
            tPage+=v.split("\n").join("\n${IndentParser.sp}");
          }else{
            tPage+=v;
          }
        }else{
          final sn = (data.length == 1 || k.isEmpty) ? -1 :0;
          tPage += IndentParser.decode(v,sn: sn,hasComment:hasComment);
        }
       
        rt.add(tPage);
    });
    
    return rt;
  }
  History? history;

  bool enable=true;
  int tabIndex=0;
  String _source="";
  set source(String source) {
      if(source.isEmpty && _source.isNotEmpty){
          return;
      }
      var tData = getTextData();
      if(source.isNotEmpty){
        tData[tabIndex] = data.length>1
          ? "${data.keys.elementAt(tabIndex)}\n${source.split("\n").map((v) => IndentParser.sp+v).join("\n")}"
          : source;
      }

      final rows = tData.join("\n").split("\n");
      //开始时间和结束时间相等  或者 名字和开始时间相等 就返回名字 不要日期 
      var nameSource = (name == startTime.toString() || startTime==endTime) ?  name: "$name $startTime~$endTime\n";

      _source= history?.data.length==1? rows.join("\n"):  "$nameSource\n${rows.map((v){
          return IndentParser.sp+v;
      }).join("\n")}\n";
    // var newP = HistoryPoint.fromStringData(name,source);
    // data = newP.data;
  }

  String get source{
    if(_source.isEmpty){
        var v = data.values.elementAt(tabIndex);
        if(v is String){
          return v;
        }else{
          return  IndentParser.decode(v,sn: -1);
        }
    }
    return _source;
  }

  String sourceCode(){
    if(_source.isEmpty){
        var tData = getTextData();
        
        final rows = tData.join("\n").split("\n");
        //开始时间和结束时间相等  或者 名字和开始时间相等 就返回名字 不要日期 
        var nameSource = (name == startTime.toString() || startTime==endTime) ?  name: "$name $startTime~$endTime\n";

        return  history?.data.length==1? rows.join("\n"):  "$nameSource\n${rows.map((v){
            return IndentParser.sp+v;
        }).join("\n")}\n";
    }
    return _source;
  }
  Map<String,List<String>> get hasMarks{
    Map<String,List<String>> marksGroup ={};
    if(history!=null){
      for(var p in history!.marks.entries){
        if(!marksGroup.containsKey(p.value.name)) marksGroup[p.value.name]= [];
        marksGroup[p.value.name]?.add(p.key);
      }
    }
    return marksGroup;
  }
  List<String>? _useAssets;
  List<String> get useAssets{
      if(_useAssets!=null) return _useAssets!;
      List<String> rt=[];
      var keys = HistoryMarks.values.map((e)=>e.name).join("|");
      final reg = RegExp("(img|$keys)\\.\\S+");
      data.forEach((k,v){
        if(v is String){
          final iterable = reg.allMatches(v).map((m)=> m.group(0)! ).toList();
          rt.addAll(iterable);
          return;
        }
        IndentElement.forEach(v,(p){
          if(!p.content.contains(".")) return;
          final iterable = reg.allMatches(p.content).map((m)=> m.group(0)! ).toList();
          rt.addAll(iterable);
        });
      });
      return _useAssets=rt;
  }

  static HistoryPoint fromStringData(String name,String data,{bool isSingle=false}){
    final root = IndentParser.encode(data);
    return HistoryPoint(root,name:name,isSingle: isSingle);
  }
  
  static HistoryPoint fromIndentData(String name,Map<String,dynamic> root){
    return HistoryPoint(root,name:name);
  }

  HistoryPoint(root,{this.name="",bool? isSingle}){
    if(root.isNotEmpty){
        name = name.isNotEmpty ? name: root["content"];
        //根据第一项有没有孩子来确定是多tab数据还是单页数据 
        data = (isSingle==true || (isSingle==null && IndentElement(root).minDepth == 1)) ? {"":root} : { for(var p in (root["children"] as List<dynamic>)) p["content"]:p };
    }
    startTime = 0;
    endTime = 0;
  }

  DateTime getStartTime(){
    return DateTime(startTime);
  }
  DateTime getEndTime(){
    return DateTime(endTime);
  }

  void parseName(){
    if( RegExp(r'^\d+$').hasMatch(name) ){
          var startT = int.parse(name);
          startTime = startT;
          endTime = startT+1;
        }else if(RegExp(r'([-\d]+)[～~]([-\d]+)').hasMatch(name) ){
          var m = RegExp(r'([-\d]+)[～~]([-\d]+)').firstMatch(name);
          startTime = int.parse(m!.group(1)!);
          endTime = int.parse(m.group(2)!);
          var dataStr = m.group(0)!;
          var start = name.indexOf(dataStr);
          var page0 = name.substring(start+dataStr.length);
          name = name.substring(0,start);
          var pages = <MapEntry<String,dynamic>>[];
          if(page0.isNotEmpty) {
            pages.add(MapEntry("概述", [IndentElement.simple(page0).toData()]));
          }
          pages.addAll(data.entries);
          data = Map.fromEntries(pages);
        }
  }

  List<HistoryPointSearchResult> searchKey(String key,{ int pos=-1}) {
    var rt=<HistoryPointSearchResult>[];
    List<String> tabData = getTextData(hasComment:false) ;
    for(int i=0;i<tabData.length;i++){
      var text = tabData[i];
      var matches = RegExp(key).allMatches(text);
      if(matches.isNotEmpty){
        matches.forEachIndexed((j,match) {
          rt.add(HistoryPointSearchResult(i,j,match));
        });
      }
    }
    return rt;
  }

  
}
